<template>
    <tm-app class="app">
        <view style="position:fixed;top:0;width:750rpx;background:#fff;" :style="{height: systemInfo.statusBarHeight + 'px'}"></view>
        <view class="header" :style="{ top: systemInfo.statusBarHeight + 'px' }">
            <image src="../../static/firends/right.png" class="right" @tap="goBack"></image>
            <text class="firend">申请添加好友</text>
            <view></view>
        </view>


        <view class="content1" :style="{top:`calc(100rpx + ${systemInfo.statusBarHeight}px)`}">
            <view class="box">
                <view class="title">发送添加好友申请</view>
                <uni-easyinput style="margin-top:20rpx;" :inputBorder="false" type="textarea" maxlength="100"  trim :autoHeight="true" placeholderStyle="color:#ccc;font-size:30rpx;" v-model="wording" placeholder="附言（最多100个字）" ></uni-easyinput>
            </view>

            <view class="tip" v-if="tipText">
                    <i class="tmicon tmicon-info-circle-fill"></i>
                    {{tipText}}
                </view>

        </view>

        <view class="btn_bottom_box">
            <view class="btn_main_r"  @tap="handleAddFirend">
                <text class="text">发送</text>
            </view>
            <view class="bottom_seat"></view>
        </view>



    </tm-app>
</template>
<script lang="ts" setup>
import { ref } from 'vue' 
import { onReady, onShow, onHide, onLoad, onUnload, onPageScroll } from '@dcloudio/uni-app'
import { systemInfo as systemInfoStore } from "@/store/systemInfo";
import { queryUser,addFriendByServer } from "@/api/api";
import { userData as userDataStore } from "@/store/userData";
import { delFriend,checkFriend,addFriend } from "@/hooks/imHooks"
const userData: any = userDataStore();
const systemInfo: any = systemInfoStore();
const addUserId = ref('');
const msg:any = ref(null);
const from = ref('');

const wording = ref('');
const addLoading = ref(false);

const tipText = ref('');
let tapLoading = false;

const handleAddFirend = async()=>{

    if(tapLoading){
        return;
    }

    tapLoading = true;


    if(relation.value !== uni.$TIM.TYPES.SNS_TYPE_NO_RELATION){
        AddFriendByServer();
        return;
    }

    let source = 'Web'
    if(from.value){
        source = from.value;
    }




    const obj = {
        userId:addUserId.value,
        wording:wording.value?wording.value:`你好，我是${userData.nickName||userData.id}`,
        remark:'',
        source,
    }
    const res:any = await addFriend(obj).catch(err=>{
        const obj = {
            err
        }


        const {code} = err;
        if(code === 30525){
            tipText.value ="对方不允许被添加好友"
        }
        if(code === 30515){
            tipText.value ="您已将对方加入黑名单，无法发送好友申请"
        }

    }).catch();

    const {code,data} = res;
    if(code!==0){

        uni.showToast({
            icon: "none",
            title: "申请添加好友失败，请稍后再试",
            duration: 1500,
        });

        return;
    }

    let str ="好友申请已发送";

    if(data.code===0){
        str ="已成功添加对方为好友~";
    }

    uni.showToast({
        icon: "none",
        title: str,
        duration: 1500,
    });


    //goBack();

    setTimeout(()=>{
         goBack();
    },1000) 


}

const AddFriendByServer = async()=>{
    let addSource = 'AddSource_Type_Chat'
    if(from.value){
        addSource = `AddSource_Type_${from.value}`
    }


    const params = {
        fromAccount:userData.id,
        addType:"Add_Type_Both",
        addFriendItemList:[
            {
                toAccount:addUserId.value,
                addWording:wording.value?wording.value:`你好，我是${userData.nickName||userData.id}`,
                remark:'',
                addSource:`AddSource_Type_Chat`,
                groupName:'',

            }
        ],
        forceAddFlags:0,

    }

    const res = await addFriendByServer(params)

    const {resultItemList,actionStatus} = res;
    if(actionStatus!=='OK'){
        uni.showToast({
            icon: "none",
            title: "申请添加好友失败，请稍后再试",
            duration: 1500,
        });

        return;
    }


    const { resultCode } = resultItemList[0];

    if(resultCode===30516){

        uni.showToast({
            icon: "none",
            title: "对方不允许任何人添加好友",
            duration: 1500,
        });

        return
    }else if(resultCode===30539){

        uni.showToast({
            icon: "none",
            title: "好友申请已发送",
            duration: 1500,
        });
    }else if(resultCode===0){

        uni.showToast({
            icon: "none",
            title: "已成功添加对方为好友",
            duration: 1500,
        });
    }else{

        uni.showToast({
            icon: "none",
            title: "已成功添加对方为好友",
            duration: 1500,
        });
    }

    setTimeout(()=>{
         goBack();
    },1000)


}

const relation = ref('');

const check = async (userId: string) => {
    if (!uni.$chat_isSDKReady) {
        setTimeout(() => {
            check(userId);
        }, 200);
        return
    }

    const res: any = await checkFriend([userId]);
    const { code, data } = res;
    if (code !== 0) {
        uni.showToast({
            icon: "none",
            title: '检查胖友关系失败~',
            duration: 1500,
        });
        return
    }



    relation.value=data.successUserIDList[0].relation;



}


const goBack = ()=>{
    const pages = getCurrentPages();
    const prevurl = pages[pages.length - 2].route;
    if(prevurl==='pages/personalCenter/userSimple'){
        uni.navigateBack({
            delta: 2 // 返回两级页面
        })
    }else{
        uni.navigateBack()
    }



}

onShow(()=>{
    tapLoading = false;
})

onLoad((option:any)=>{
    if(option.userId){
        addUserId.value = option.userId;
        check(option.userId);
    }

    if(option.from){
        from.value = option.from;
    }
})


</script>
<style lang="scss" scoped>
.app {
    .header {
        position:fixed;
        width:750rpx;
        z-index:100;
        top:0;
        left:0;
        padding: 0 30rpx;
        display: flex;
        height: 100rpx;
        align-items: center;
        justify-content: space-between;
        height:100rpx;
        // position: absolute;
        // top: 0;
        // left: 0;
        width: 750rpx;
        background-color: #FFFFFF;

        .right {
            width: 48rpx;
            height: 48rpx;

        }

        .firend {
            font-size: 34rpx;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 600;
            color: #000000;
        }

    }


    .content1{
        position:absolute;
        width:750rpx;
        bottom:0;
        left:0;
        padding-bottom: calc(constant(safe-area-inset-bottom) + 20rpx);
        padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);
        .box{
            padding:30rpx;
            background:#fff;
            .title{
                font-size: 30rpx;
                font-weight: 400;
                color: $slim-text3;
            }
        }

        .tip{
                padding:0 30rpx;
                margin-top:30rpx;
                color:#fd5745;
                font-size:28rpx;
            }

        .btn_main {
            display:block;
            height:80rpx;
            border-radius:40rpx;
            line-height:80rpx;
            z-index:100;
            margin-top:30rpx !important;
        }
        
    }


}
</style>    